/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.uoc.tdp.pac4.repara;

import edu.uoc.tdp.pac4.beans.Mecanic;
import edu.uoc.tdp.pac4.beans.Reparacio;
import edu.uoc.tdp.pac4.beans.ReparacioMecanic;
import edu.uoc.tdp.pac4.beans.SolicitudDetall;
import edu.uoc.tdp.pac4.cliente.Principal;
import edu.uoc.tdp.pac4.comun.GestorReparacionesInterface;
import edu.uoc.tdp.pac4.comun.PAC4Exception;
import edu.uoc.tdp.pac4.i18n.TDSLanguageUtils;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author rfebrerg
 */
public class GestionAprobacionSolicitudes extends javax.swing.JInternalFrame {

    private GestorReparacionesInterface conexion;
    
    private final String URL = "localhost";
    private final String JNDI_NAME = "Serv_Reparaciones";
    private final int PORT = 1099;
    private ArrayList<Mecanic> mecanics;
    /**
     * Creates new form GestionReparaciones
     */
    public GestionAprobacionSolicitudes() throws PAC4Exception {

        initComponents();
        conectarServerRMI();
        getInitialData();
    }

    private void conectarServerRMI() {
        try {
            Registry registry = LocateRegistry.getRegistry(URL, PORT);
            this.conexion = (GestorReparacionesInterface) registry.lookup(JNDI_NAME);
        } catch (NotBoundException e) {
            e.printStackTrace();
            System.exit(0);
        } catch (RemoteException e) {
            Principal.showError(e.getMessage());
            e.printStackTrace();
            System.exit(0);
        } catch (Exception e) {
            Principal.showError(e.getMessage());
            e.printStackTrace();
            System.exit(0);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        SolicitutsTable = new javax.swing.JTable();
        jBAprobar = new javax.swing.JButton();
        jBDenegar = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, TDSLanguageUtils.getMessage("Reparaciones.TtlReparaciones"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, java.awt.Color.darkGray));

        SolicitutsTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null}
            },
            new String [] {
                "Id", "Estado", "Mecánico", "Asignada", "Contador", "Observaciones", "NumCom", "Fecha Inicio", "Fecha fin"
            }
        ));
        jScrollPane2.setViewportView(SolicitutsTable);

        jBAprobar.setText(TDSLanguageUtils.getMessage("Reparaciones.BtAprobarSolicitud"));
        jBAprobar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBAprobarActionPerformed(evt);
            }
        });

        jBDenegar.setText(TDSLanguageUtils.getMessage("Reparaciones.BtDenegarSolicitud"));
        jBDenegar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBDenegarActionPerformed(evt);
            }
        });

        jButton1.setText(TDSLanguageUtils.getMessage("Reparaciones.BtActualizar"));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 555, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jBAprobar)
                .addGap(18, 18, 18)
                .addComponent(jBDenegar))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBAprobar)
                    .addComponent(jBDenegar)
                    .addComponent(jButton1))
                .addContainerGap(102, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(11, 11, 11))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private int getSelectedTable()
    {
         int row=SolicitutsTable.getSelectedRow();
        int idSol=Integer.parseInt(SolicitutsTable.getValueAt(row, 0).toString());
        return idSol;
    }
    private void jBAprobarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBAprobarActionPerformed
        
        int idSol=getSelectedTable();
        try {
            int resultado=conexion.insertReparacionSolicitud(idSol, 1,2);
            if(resultado==0)
                Principal.showError(TDSLanguageUtils.getMessage("Reparaciones.ErrorAprobar"));
            else
            {
                Principal.showMessage(TDSLanguageUtils.getMessage("Reparaciones.SolicitudAprobada"),TDSLanguageUtils.getMessage("Reparaciones.SolicitudAprobada"));
                getAllSolicitudes();
            }
        } catch (PAC4Exception ex) {
            Principal.showError(ex.getMessage());
            Logger.getLogger(GestionAprobacionSolicitudes.class.getName()).log(Level.SEVERE, null, ex);
        } catch (RemoteException ex) {
            Principal.showError(ex.getMessage());
            Logger.getLogger(GestionAprobacionSolicitudes.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Principal.showError(ex.getMessage());
            Logger.getLogger(GestionAprobacionSolicitudes.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jBAprobarActionPerformed

    private void jBDenegarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBDenegarActionPerformed
     int idSol=getSelectedTable();
     try {
            int resultado=conexion.insertReparacionSolicitud(idSol, 1,3);
            
           if(resultado==0)
                Principal.showError(TDSLanguageUtils.getMessage("Reparaciones.ErrorDenegar"));
            else
            {
                Principal.showMessage(TDSLanguageUtils.getMessage("Reparaciones.SolicitudDenegada"),TDSLanguageUtils.getMessage("Reparaciones.SolicitudDenegada"));
                getAllSolicitudes();
            }
        } catch (PAC4Exception ex) {
            Principal.showError(ex.getMessage());
            Logger.getLogger(GestionAprobacionSolicitudes.class.getName()).log(Level.SEVERE, null, ex);
        } catch (RemoteException ex) {
            Principal.showError(ex.getMessage());
            Logger.getLogger(GestionAprobacionSolicitudes.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Principal.showError(ex.getMessage());
            Logger.getLogger(GestionAprobacionSolicitudes.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jBDenegarActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            getInitialData();
        } catch (PAC4Exception ex) {
            Logger.getLogger(GestionAprobacionSolicitudes.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GestionAprobacionSolicitudes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GestionAprobacionSolicitudes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GestionAprobacionSolicitudes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GestionAprobacionSolicitudes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable SolicitutsTable;
    private javax.swing.JButton jBAprobar;
    private javax.swing.JButton jBDenegar;
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables

    private void getInitialData() throws PAC4Exception {
        getAllSolicitudes();
       
    }

    private void getAllSolicitudes() throws PAC4Exception {
        try {

            DefaultTableModel dtm = new DefaultTableModel(0, 0);
             String header[] = new String[]{TDSLanguageUtils.getMessage("Reparaciones.Solicitud"), 
                TDSLanguageUtils.getMessage("Reparaciones.Comentarios"),
                TDSLanguageUtils.getMessage("Reparaciones.FechaAlta"),
                TDSLanguageUtils.getMessage("Reparaciones.Estado"),
                TDSLanguageUtils.getMessage("Reparaciones.Cliente"),
                TDSLanguageUtils.getMessage("Reparaciones.Marca"),
                TDSLanguageUtils.getMessage("Reparaciones.Modelo"),
                TDSLanguageUtils.getMessage("Reparaciones.Matricula"),
            };
            dtm.setColumnIdentifiers(header);
            SolicitutsTable.setModel(dtm);
            int idMec=1;
            ArrayList<SolicitudDetall> solicitudes = conexion.getSolicituds();

            for (int i = 0; i < solicitudes.size(); i++) {
                Vector<Object> vdata = new Vector<Object>();
                vdata.add(solicitudes.get(i).getSol().getNumSol());
                vdata.add(solicitudes.get(i).getSol().getComentaris());
                vdata.add(solicitudes.get(i).getSol().getDataAlta());
                //vdata.add(solicitudes.get(i).getSol().getNumPoliza());
                vdata.add(solicitudes.get(i).getEstado());
                vdata.add(solicitudes.get(i).getClient().getNom());
                vdata.add(solicitudes.get(i).getVehicle().getMarca());
                vdata.add(solicitudes.get(i).getVehicle().getModel());
                vdata.add(solicitudes.get(i).getVehicle().getMatricula());
                //vdata.add(solicitudes.get(i).getVehicle().getColor());
                dtm.addRow(vdata);
            }
            if(solicitudes.size()>0) {
                SolicitutsTable.setRowSelectionInterval(0, 0);
            }
             TableRowSorter sorter = new TableRowSorter(	dtm);
            SolicitutsTable.setRowSorter(sorter);
        } catch (RemoteException ex) {
            Principal.showError(ex.getMessage());
            Logger.getLogger(GestionAprobacionSolicitudes.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Principal.showError(ex.getMessage());
            Logger.getLogger(GestionAprobacionSolicitudes.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


}
